package com.dy.hander;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
/**
 * @ClassName:
 * @Author: 仄言in
 * @Desctiption: (描述)：全局异常拦截器，拦截控制层所有请求，当有异常时跳转不同的错误页面
 * @Date: 2021/5/7 11:19
 * @Version 1.0 (版本)
 */
@ControllerAdvice
public class ExceptionHandler {
    private final Logger log= LogManager.getLogger(ExceptionHandler.class);

    @org.springframework.web.bind.annotation.ExceptionHandler(Exception.class)
    public ModelAndView exceptionHandler(HttpServletRequest request,Exception e) throws Exception {
        log.error("Request URL : {},Exception : {}",request.getRequestURI(),e);

        /**
         * 判断ResponseStatus.class是否为空，不为空就抛出异常，让springboot去处理这个异常，让它跳转到404页面
         */
        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class)!=null) {
            throw e;
        }
        ModelAndView mv = new ModelAndView();
        mv.addObject("url",request.getRequestURI());
        mv.addObject("exception",e);
        mv.setViewName("error/error");
        return mv;
    }
}
